import { type NextRequest, NextResponse } from "next/server"
import { v4 as uuidv4 } from "uuid"
import { getDb } from "@/lib/db-sqlite"

// 投票
export async function POST(request: NextRequest, { params }: { params: { id: string } }) {
  try {
    // 正确处理 params
    const { id: pollId } = await params
    const { optionId, voterId } = await request.json()

    if (!optionId || !voterId) {
      return NextResponse.json({ error: "Invalid data" }, { status: 400 })
    }

    console.log(`Processing vote for poll ${pollId}, option ${optionId}, voter ${voterId}`)

    const db = getDb()

    // 检查投票是否存在
    const poll = db
      .prepare(`
      SELECT * FROM polls
      WHERE id = ?
    `)
      .get(pollId)

    if (!poll) {
      console.log(`Poll ${pollId} not found`)
      return NextResponse.json({ error: "Poll not found" }, { status: 404 })
    }

    // 检查投票是否活跃
    if (!poll.active) {
      console.log(`Poll ${pollId} is not active`)
      return NextResponse.json({ error: "Poll is not active" }, { status: 400 })
    }

    // 检查选项是否存在
    const option = db
      .prepare(`
      SELECT * FROM poll_options
      WHERE id = ? AND poll_id = ?
    `)
      .get(optionId, pollId)

    if (!option) {
      console.log(`Option ${optionId} not found for poll ${pollId}`)
      return NextResponse.json({ error: "Option not found" }, { status: 404 })
    }

    // 检查用户是否已经投票
    const existingVote = db
      .prepare(`
      SELECT * FROM vote_records
      WHERE poll_id = ? AND voter_id = ?
    `)
      .get(pollId, voterId)

    if (existingVote) {
      console.log(`Voter ${voterId} has already voted for poll ${pollId}`)
      return NextResponse.json({ error: "您已经参与过此投票" }, { status: 400 })
    }

    // 开始事务
    const transaction = db.transaction(() => {
      // 记录投票
      db.prepare(`
        INSERT INTO vote_records (id, poll_id, voter_id, created_at)
        VALUES (?, ?, ?, ?)
      `).run(uuidv4(), pollId, voterId, new Date().toISOString())

      // 增加选项票数
      db.prepare(`
        UPDATE poll_options
        SET votes = votes + 1
        WHERE id = ?
      `).run(optionId)
    })

    // 执行事务
    transaction()

    console.log(`Vote recorded successfully for poll ${pollId}, option ${optionId}`)
    return NextResponse.json({ success: true })
  } catch (error: any) {
    console.error("Error voting:", error)
    return NextResponse.json({ error: error.message || "Failed to vote" }, { status: 500 })
  }
}
